package org.spring.springsecrty;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;
import java.net.Authenticator;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    UserDetailsService12 userDetailsService;


    @Autowired
    private DataSource dataSource;

 /*  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }*/
 //配置对象
 @Bean
 public PersistentTokenRepository persistentTokenRepository() {
     JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
     jdbcTokenRepository.setDataSource(dataSource);
     //jdbcTokenRepository.setCreateTableOnStartup(true);
     return jdbcTokenRepository;
 }



    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.exceptionHandling().accessDeniedPage("/unauth.html");
        // 配置认证
        http.formLogin()
                .loginPage("/index.html") // 配置哪个 url 为登录页面
                .loginProcessingUrl("/user/login") // 设置哪个是登录的 url。
                .defaultSuccessUrl("/success").
                permitAll() // 登录成功之后跳转到哪个 url
                .failureUrl("/unauth.html")

                .and().authorizeRequests().antMatchers("/", "/user/login"
        ,"/unauth.html").permitAll()  //不需要验证的url

             // .antMatchers("/success").hasAuthority("admin")
               // .antMatchers("/success").hasAnyAuthority("role","admin1")
                //.antMatchers("/success").hasRole("admin")
               .antMatchers("/success").hasAnyRole("admin,haha")
                .anyRequest().authenticated()

         .and().rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60)
                .userDetailsService(userDetailsService)
                .and().csrf().disable();

        // 关闭 csrf
        //  http.csrf().disable();

    }




    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
